package com.football.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.football.springboot.entity.*;
import com.football.springboot.mapper.GameDataMapper;
import com.football.springboot.mapper.GameMapper;
import com.football.springboot.service.*;
import com.football.springboot.vo.GameQueryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.football.springboot.common.Return;
import com.football.springboot.common.Result;
//导入service
//导入entity

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 李越
 * @since 2023-02-22
 */
@Api(tags = "比赛管理")
@RestController
@RequestMapping("/game")
public class GameController {

    @Resource
    private IGameService gameService;

    @Resource
    private GameMapper gameMapper;

    @Resource
    private IGameDataService gameDataService;

    @Resource
    private ITeamDataSingleService teamDataSingleService;

    @Resource
    private ITeamDataService teamDataService;

    @Resource
    private ILeagueService leagueService;

    @Resource
    private ITeamService teamService;

    // 新增或者更新
    @ApiOperation("新增或者更新")
    @PostMapping("/saveOrUpdate")
    public Result save(@RequestBody Game game) {
        gameService.saveOrUpdate(game);
        return Result.success();
    }


    //删除
    @ApiOperation("删除")
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        gameService.removeById(id);
        return Result.success();
    }

    //批量删除
    @ApiOperation("批量删除")
    @PostMapping("/delete/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        gameService.removeByIds(ids);
        return Result.success();
    }

    //查询全部
    @ApiOperation("查询全部")
    @GetMapping("/findall")
    public Result findAll() {
        return Result.success(gameService.list());
    }




    //根据id查找
    @ApiOperation("根据id查找")
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(gameService.getById(id));
    }



    //前台比赛赛程分页查询
    @ApiOperation("前台比赛赛程分页查询")
    @GetMapping("/front/pageGame")
    public Return frontpageGame(@RequestParam Integer current,
                                @RequestParam Integer limit,
                                GameQueryVo gameQueryVo){
        //创建page对象,传递当前页数current,每页记录数limit
        Page<Game> page = new Page<>(current,limit);
        //构建条件 模糊查询
        QueryWrapper<Game> queryWrapper = new QueryWrapper<>();
        QueryWrapper<League> queryWrapperleague = new QueryWrapper<>();
        Integer homeTeam = gameQueryVo.getHomeTeam();
        Integer awayTeam = gameQueryVo.getAwayTeam();
        String leagueSeason = gameQueryVo.getLeagueSeason();
        Integer leagueId = gameQueryVo.getLeagueId();
        Integer gameRounds = gameQueryVo.getGameRounds();

        //主场球队查询
        queryWrapper.eq(homeTeam!=null,"home_team",homeTeam);

        //客场球队查询
        queryWrapper.eq(awayTeam!=null,"away_team",awayTeam);

        //根据联赛查询
        queryWrapper.eq(leagueId!=null,"league_id",leagueId);


        //根据赛季查询
        List<Integer> ids = null;
        if (!StringUtils.isEmpty(leagueSeason)){
            queryWrapperleague.like("league_season",leagueSeason);
            List<League> leagues = leagueService.list(queryWrapperleague);

            ids = leagues.stream().map(League::getId).collect(Collectors.toList());
            queryWrapper.in(!ids.isEmpty(),"league_id",ids);
            //查询不到时,返回空数据
            if (ids.isEmpty()){
                Page<Game> pagenull = new Page<>();
                return Return.ok().put("pageGame",pagenull).put("total",0);
            }
        }


        //根据轮次查询
        queryWrapper.eq(gameRounds!=null,"game_rounds",gameRounds);

        queryWrapper.orderByDesc("game_time");
        Page<Game> pageGame = gameService.page(page,queryWrapper);
        List<Game> records = pageGame.getRecords();
        System.err.println(records);
        records.forEach(game -> {
            //将主场球队信息插入到列表中
            game.setHometeaminfo(gameMapper.getHomeTeaminfo(game.getId()));
            //将客场球队信息插入到列表中
            game.setAwayteaminfo(gameMapper.getAwayTeaminfo(game.getId()));
            //将联赛信息插入到列表中
            game.setLeague(gameMapper.getLeagueinfo(game.getId()));
            //将比赛数据插入到列表中 存在才插入
            game.setGameData(gameService.getGameData(game.getId()));
        });


        return Return.ok().put("pageGame",pageGame).put("total",pageGame.getTotal());
    }
    //后台管理分页查询
    @ApiOperation("分页查询")
    @GetMapping("/pageGame")
    public Return pageGame(@RequestParam Integer current,
                           @RequestParam Integer limit,
                           GameQueryVo gameQueryVo) {

        //创建page对象,传递当前页数current,每页记录数limit
        Page<Game> page = new Page<>(current,limit);
        //构建条件 模糊查询
        QueryWrapper<Game> queryWrapper = new QueryWrapper<>();
        Page<Game> pagenull = new Page<>();
        Integer homeTeam = gameQueryVo.getHomeTeam();
        Integer awayTeam = gameQueryVo.getAwayTeam();
        //String leagueSeason = gameQueryVo.getLeagueSeason();
        Integer leagueId = gameQueryVo.getLeagueId();
        Integer gameRounds = gameQueryVo.getGameRounds();

        //主场球队查询
        queryWrapper.eq(homeTeam!=null,"home_team",homeTeam);

        //客场球队查询
        queryWrapper.eq(awayTeam!=null,"away_team",awayTeam);

        //根据联赛查询
        queryWrapper.eq(leagueId!=null,"league_id",leagueId);

        //根据赛季查询
//        if(!StringUtils.isEmpty(leagueSeason)){
//            queryWrapper.like("league.league_season",leagueSeason);
//        }

        //根据轮次查询
        queryWrapper.eq(gameRounds!=null,"game_rounds",gameRounds);

        queryWrapper.orderByDesc("game_time");
        Page<Game> pageGame = gameService.page(page,queryWrapper);
        List<Game> records = pageGame.getRecords();
        System.out.println(records);

        records.forEach(game -> {
            //将主场球队信息插入到列表中
            game.setHometeaminfo(gameMapper.getHomeTeaminfo(game.getId()));
            //将客场球队信息插入到列表中
            game.setAwayteaminfo(gameMapper.getAwayTeaminfo(game.getId()));
            //将联赛信息插入到列表中
            game.setLeague(gameMapper.getLeagueinfo(game.getId()));

        });

        return Return.ok().put("pageGame",pageGame).put("total",pageGame.getTotal());
    }


    //查看比赛详细数据
    @ApiOperation("查看比赛详细数据")
    @GetMapping("/getGamedata")
    public Result getGamedata(@RequestParam Integer gameId){
        GameData gameData = gameService.getGameData(gameId);
        if(gameData!=null){
            gameData.setHomeTeamInfo(teamService.getById(gameService.getById(gameId).getHomeTeam()));

            gameData.setAwayTeamInfo(teamService.getById(gameService.getById(gameId).getAwayTeam()));
        }
        System.err.println(gameData);
        return Result.success(gameData);
    }

    //编辑比赛详细数据(会同时编辑球队的赛季比赛数据（通过球队的单场比赛数据作为中介） 分主客场 给team_data加个主队客队区分的字段)
    @ApiOperation("编辑比赛详细数据")
    @PostMapping("/saveGameData")
    public Result saveGameData(@RequestBody GameData gameData,
                               @RequestParam Integer gameId){
        //把gameId关联给比赛数据表的game_id
        gameData.setGameId(gameId);
        System.out.println(gameData);
        UpdateWrapper<GameData> updateWrapper = new UpdateWrapper<>();

        QueryWrapper<GameData> queryWrapper = new QueryWrapper<>();
        QueryWrapper<TeamData> queryWrapperteam = new QueryWrapper<>();
        UpdateWrapper<TeamDataSingle> updateWrapperhomesingle = new UpdateWrapper<>();
        UpdateWrapper<TeamDataSingle> updateWrapperawaysingle = new UpdateWrapper<>();
        UpdateWrapper<TeamData> updateWrapperhome = new UpdateWrapper<>();
        UpdateWrapper<TeamData> updateWrapperaway = new UpdateWrapper<>();
        //比赛数据表里没有就新增 有就修改
        if (gameDataService.getOne(queryWrapper.eq("game_id", gameData.getGameId())) == null) {
            //新增主场球队的单场比赛数据
            TeamDataSingle homegamedatasingle = teamDataSingleService.homegamedatasingle(gameData,gameId);
            teamDataSingleService.save(homegamedatasingle);

            //新增主场球队比赛数据时更新该主场球队的赛季数据
            if(teamDataService.getOne(queryWrapperteam.eq("team_id",homegamedatasingle.getTeamId())// 该行数据没有创建时
                    .eq("league_id",gameService.getLeagueinfo(homegamedatasingle.getGameId()).getId()).eq("home_away","主场"))==null){
            TeamData homegamedata = teamDataService.addgamedata(homegamedatasingle);
            homegamedata.setHomeAway("主场");
            teamDataService.save(homegamedata);
            }else{//更新已经存在的那一行代表这个球队这个赛季的联赛的数据 加数据
                //根据那一行数据的teamid和leagueid进行更新 先找到他
            Integer teamId = homegamedatasingle.getTeamId();
            Integer leagueId= gameService.getLeagueinfo(homegamedatasingle.getGameId()).getId();
            TeamData updatehomegamedata = teamDataService.getupdategamedata(teamId,leagueId,"主场");
            TeamData homegamedata = teamDataService.updategamedata(updatehomegamedata,homegamedatasingle);
            teamDataService.update(homegamedata,updateWrapperhome.eq("team_id",teamId).eq("league_id",leagueId).eq("home_away","主场"));
            }


            //新增客场球队的单场比赛数据
            TeamDataSingle awaygamedatasingle = teamDataSingleService.awaygamedatasingle(gameData,gameId);
            teamDataSingleService.save(awaygamedatasingle);

            //新增客场球队比赛数据时更新该客场球队的赛季数据

            if(teamDataService.getOne(queryWrapperteam.eq("team_id",awaygamedatasingle.getTeamId())// 该行数据没有创建时
                    .eq("league_id",gameService.getLeagueinfo(awaygamedatasingle.getGameId()).getId()).eq("home_away","客场"))==null){
                TeamData awaygamedata = teamDataService.addgamedata(awaygamedatasingle);
                awaygamedata.setHomeAway("客场");
                teamDataService.save(awaygamedata);
            }else{//更新已经存在的那一行代表这个球队这个赛季的联赛的数据 加数据
                //根据那一行数据的teamid和leagueid进行更新 先找到他
                Integer teamId = awaygamedatasingle.getTeamId();
                Integer leagueId= gameService.getLeagueinfo(awaygamedatasingle.getGameId()).getId();
                TeamData updateawaygamedata = teamDataService.getupdategamedata(teamId,leagueId,"客场");
                TeamData awaygamedata = teamDataService.updategamedata(updateawaygamedata,awaygamedatasingle);
                teamDataService.update(awaygamedata,updateWrapperaway.eq("team_id",teamId).eq("league_id",leagueId).eq("home_away","客场"));
            }


            //新增比赛数据
            return Result.success(gameDataService.save(gameData));
        }else{
            //先找出修改前的单场比赛数据(要先获取没修改之前单场比赛的数据，通过胜平负还有各种逻辑关系，才能统计赛季数据)
            TeamDataSingle homegamedatasinglebefore = teamDataSingleService.getteamdatasingle(gameService.getById(gameId).getHomeTeam(),gameId);
            TeamDataSingle awaygamedatasinglebefore = teamDataSingleService.getteamdatasingle(gameService.getById(gameId).getAwayTeam(),gameId);
            //修改主场球队的单场比赛数据
            TeamDataSingle homegamedatasingle = teamDataSingleService.homegamedatasingle(gameData,gameId);
            teamDataSingleService.update(homegamedatasingle,
                    updateWrapperhomesingle
                    .eq("game_id",gameId)
                    .eq("team_id",gameService.getById(gameId).getHomeTeam()));

            //修改主场球队比赛数据时更新该主场球队的赛季数据
            Integer teamId = homegamedatasingle.getTeamId();
            Integer leagueId= gameService.getLeagueinfo(homegamedatasingle.getGameId()).getId();
            TeamData updatehomegamedata = teamDataService.getupdategamedata(teamId,leagueId,"主场");

            TeamData homegamedata = teamDataService.updategamedataexist(updatehomegamedata,homegamedatasinglebefore,homegamedatasingle);
            teamDataService.update(homegamedata,updateWrapperhome.eq("team_id",teamId).eq("league_id",leagueId).eq("home_away","主场"));

            //先找出修改前的单场比赛数据(要先获取没修改之前单场比赛的数据，通过胜平负还有各种逻辑关系，才能统计赛季数据)


            //修改客场球队的单场比赛数据
            TeamDataSingle awaygamedatasingle = teamDataSingleService.awaygamedatasingle(gameData,gameId);
            teamDataSingleService.update(awaygamedatasingle,
                    updateWrapperawaysingle
                    .eq("game_id",gameId)
                    .eq("team_id",gameService.getById(gameId).getAwayTeam()));

            //修改客场球队比赛数据时更新该客场球队的赛季数据
            Integer teamIdaway = awaygamedatasingle.getTeamId();
            Integer leagueIdaway= gameService.getLeagueinfo(awaygamedatasingle.getGameId()).getId();
            TeamData updateawaygamedata = teamDataService.getupdategamedata(teamIdaway,leagueIdaway,"客场");

            TeamData awaygamedata = teamDataService.updategamedataexist(updateawaygamedata,awaygamedatasinglebefore,awaygamedatasingle);
            teamDataService.update(awaygamedata,updateWrapperaway.eq("team_id",teamIdaway).eq("league_id",leagueIdaway).eq("home_away","客场"));


            //修改比赛数据
            return Result.success(gameDataService.update(gameData,updateWrapper.eq("game_id",gameId)));
        }
    }



    //前台查询一场比赛信息（GameDetail用）
    @ApiOperation("前台查询一场比赛信息")
    @GetMapping("/front/getgamedetail")
    public Result getgamedetail(@RequestParam Integer gameId){
        Game game = gameService.getById(gameId);
        game.setLeague(leagueService.getById(game.getLeagueId()));
        QueryWrapper<GameData> queryWrappergd = new QueryWrapper<>();
        queryWrappergd.eq("game_id",gameId);
        game.setGameData(gameDataService.getOne(queryWrappergd));

        return Result.success(game);
    }



}

